package easy.有效的括号;

import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * 有效的括号
 *
 * @author codex
 * @since 2021-09-25
 */
public class ValidParentheses {
    
    public static boolean isValid(String s) {
        // s = {[]}
        Map<Character, Character> map = new HashMap<>(3);
        map.put(')', '(');
        map.put('}', '{');
        map.put(']', '[');
        
        Deque<Character> deque = new LinkedList<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (map.containsKey(c)) {
                if (deque.isEmpty() || !deque.peek().equals(map.get(c))) {
                    return false;
                }
                deque.pop();
            } else {
                deque.push(c);
            }
        }
    
        return deque.isEmpty();
    }
    
    public static void main(String[] args) {
        String s = "{[]}";
        boolean valid = isValid(s);
        System.out.println(valid);
    }
}
